import Vue from 'vue'
import Vuex from 'vuex'
import App from './App.vue'
import ViewUI from 'view-design';
import 'view-design/dist/styles/iview.css';
import './my-theme.less';
import VueRouter from 'vue-router'
import Axios from 'axios'
import * as types from './store/types'
import hasPerm from './store/hasPermission.js'
import utils from './utils/utils'
import validateUtils from './utils/validate_utils'
import myElement from './comp_process/applyVue/print/getElement'
import Print from 'vue-print-nb'
import myAjax from "./ajax_util"

import IntroJs from 'intro.js'
import 'intro.js/introjs.css';
Vue.prototype.IntroJs = IntroJs;

Vue.use(Print);

import mixin from "./utils/mixin";
Vue.mixin(mixin);

Vue.use(Vuex);
Vue.use(VueRouter);
Vue.use(ViewUI);
Vue.use(hasPerm);
Vue.prototype.myAjax = myAjax;
Vue.prototype.utils = utils;
Vue.prototype.validateUtils = validateUtils
Vue.prototype.axios = Axios;
Vue.prototype.myElement = myElement;

const store = new Vuex.Store({
	state: {
		selected_tenant: 0,
		general_data: 0,
		token: null,
		title: '',
		permissions: [],
		addRouters: [],
		routers: routes,
		user: {},
		tabs: null,
		printHtml: "",
		toPage: "",
		toToken: "",
		target: "",

	},
	mutations: {
		change_selected_tenant(state, value) {
			state.selected_tenant = value
		},
		change_general_data(state, newdata) {
			state.general_data = newdata;
		},
		[types.LOGIN]: (state, data) => {
			localStorage.token = data;
			state.token = data;
		},
		[types.LOGOUT]: (state) => {
			localStorage.removeItem('token');
			state.token = null;
			localStorage.removeItem('permissions');
			localStorage.removeItem('menu');
			state.permissions = [];
			state.addRouters = [];
			state.routers = routes;
			var cookieText = "Authorization=; path=/"
			document.cookie = cookieText;
			localStorage.removeItem('user');
			state.user = {};
			sessionStorage.removeItem('tabs');
			state.tabs = null
		},
		[types.TITLE]: (state, data) => {
			state.title = data;
		},
		[types.PERM]: (state, data) => {
			localStorage.permissions = data;
			state.permissions = JSON.parse(data);
		},
		[types.USER]: (state, data) => {
			localStorage.user = data;
			state.user = JSON.parse(data);
		},
		SET_ROUTERS: (state, routers) => {
			state.addRouters = routers
			state.routers = routes.concat(routers) //将固定路由和新增路由进行合并, 成为本用户最终的全部路由信息
		},
		tabs(state, value) {
			sessionStorage.tabs = JSON.stringify(value)
			state.tabs = value
		},
		printHtml(state, value) {
			state.printHtml = value
		},
	},
	actions: {
		GenerateRoutes({
			commit
		}, userPermission) {
			//生成路由
			const menus = userPermission;
			//声明 该角色可用的路由
			let accessedRouters;
			if (userPermission.indexOf("系统管理员") > -1) {
				//如果角色里包含'管理员',那么所有的路由都可以用
				accessedRouters = asyncRouter
			} else {
				//否则需要通过以下方法来筛选出本角色可用的路由
				accessedRouters = filterAsyncRouter(asyncRouter, menus)
			}
			//执行设置路由的方法
			commit('SET_ROUTERS', accessedRouters);
			//console.log("-----state.routers--------",store.state.routers);
		}
	}
})


// const brief = resolve => require(['./components_brief/brief'],resolve)
// import b_general from './components_brief/b_general'
// import b_dim from './components_brief/b_dim'
// import b_tenant from './components_brief/b_tenant'

const chatter_page = resolve => require(['./comp_chatter/chatter_page'], resolve)
// const knowledge_page = resolve => require(['./comp_knowledge/knowledge_page'],resolve)
// const know_edit = resolve => require(['./comp_knowledge/know_edit'],resolve)

// const mainpage = resolve => require(['./components/mainpage'],resolve)
const usermain = resolve => require(['./comp_user/user_main'], resolve)

const processmain = resolve => require(['./comp_process/mainpage'], resolve)
// const businessmain = resolve => require(['./comp_business/bus_main'], resolve)
const personalCenter = resolve => require(['./comp_persomal/personal_center'], resolve)

// const login = resolve => require(['./comp_user/fourA_login'], resolve)
const login = resolve => require(['./comp_user/login'], resolve)
// const fourAlogin = resolve => require(['./comp_user/fourA_login'], resolve)
const registered = resolve => require(['./comp_user/registered'], resolve)
const tagmodel = resolve => require(['./comp_process/applyVue/apply_model/tag_information/tag_model'], resolve)
// 我的新增
const hot = resolve => require(['./comp_process/applyVue/apply_model/hot/hotlabels'], resolve)
const hottwo = resolve => require(['./comp_process/applyVue/apply_model/hottwo/table'], resolve)

// E:\Mydocument\Inspur\workspace2\web\src\comp_process\applyVue\apply_model\tag_information
// import login from "./comp_user/login"
// import registered from './comp_user/registered'
import print from './comp_process/applyVue/print/print_test.vue'
import previewFile from './base/preview_file.vue'
const asyncRouter = [
	// {
	//   path: '/a',
	//   component: mainpage,
	//   menu: 'article'
	// },
	// {
	//   path: '/healthy',
	//   component: brief,
	//   children: [
	//     {
	//       path: 'general',
	//       component: b_general,
	//       menu: 'healthy_general'
	//     },
	//     {
	//       path: '',
	//       component: b_general,
	//       menu: 'healthy_general'
	//     },
	//     {
	//       path: 'dim',
	//       component: b_dim,
	//       menu: 'healthy_dim'
	//     },
	//     {
	//       path: 'tenant',
	//       component: b_tenant,
	//       menu: 'healthy_tenant'
	//     }
	//   ]
	// },
	// {
	//   path: '/chatter',
	//   component: chatter_page,
	//   meta:{
	//     name:"智能客服助手"
	//   },
	//   menu: 'chatter:list'
	// },
	// {
	//   path: '/knowledge',
	//   component: knowledge_page,
	//   meta:{
	//     name:"问答知识库-所有主题类型"
	//   },
	//   menu: 'knowledge_list'
	// },
	// {
	//   path: '/know_edit/:id',
	//   name:"know_edit",
	//   component: know_edit,
	//   meta:{
	//     name:"问答知识库 - 知识编辑"
	//   },
	//   menu: 'knowledge_update'
	// },
	// {
	//   path: '/usermain',
	//   component: usermain,
	//   meta:{
	//     requireAuth: true,
	//     name:"用户管理  /"
	//   },
	//   menu: 'projectList'
	// },
	// {
	//   path: '/processmain',
	//   name: 'processmain',
	//   component: processmain,
	//   meta:{
	//     requireAuth: true,
	//   },
	//   menu: 'processmain'
	// },
];

import chatter from "./comp_chatter/chatter_page"
const routes = [
	{
		path: '/testchatter',
		component: chatter,
		meta: {
			name: "chatter"
		}
	},
	{
		path: '/',
		component: login,
		meta: {
			name: "登录"
		}
	},
	// {
	// 	path: '/fourAlogin',
	// 	component: fourAlogin,
	// 	meta: {
	// 		name: "4A登录"
	// 	}
	// },
	{
		path: '/other_page/print',
		name: 'print',
		component: print,
		meta: {
			requireAuth: true,
		},
	},
	{
		path: '/other_page/previewFile',
		name: 'previewFile',
		component: previewFile,
		meta: {
			requireAuth: true,
		},
	},
	// {
	//   path: '/chatter',
	//   component: chatter_page,
	//   meta:{
	//     name:"智能客服助手"
	//   },
	//   menu: 'chatter:list'
	// },
	{
		path: '/processmain',
		name: 'processmain',
		component: processmain,
		meta: {
			requireAuth: true,
		},
		menu: 'processmain'
	},
	{
		path: '/login',
		component: login,
		meta: {
			name: "登录"
		}
	},
	{
	  path: '/chatter',
	  component: chatter_page,
	  meta:{
	    name:"智能客服助手"
	  },
	  menu: 'chatter:list'
	},
	{
		path: '/registered',
		component: registered,
		meta: {
			name: "注册"
		}
	},
  {
    path: '/tagInformation',
    component: tagmodel,
    meta: {
      name: "标签信息"
    }
  },
//   ========================================================================================================================
  {
        path: '/hotlabels',
        component: hot,
        meta: {
          name: "热点标签"
        },
    },
	{
		path: '/table',
		component: hottwo,
		meta: { name: 'Table'}
	},
	
//   ========================================================================================================================

	{
		path: '/usermain',
		component: usermain,
		meta: {
			requireAuth: true,
			name: "用户管理  /"
		},
		menu: 'projectList'
	},
	{
		path: '/personalCenter',
		component: personalCenter,
		meta: {
			requireAuth: true,
			name: "个人中心"
		}
	}
];

// 页面刷新时，重新赋值token
if (window.localStorage.getItem('token')) {
	store.commit(types.LOGIN, window.localStorage.getItem('token'));
	store.commit("tabs", JSON.parse(window.sessionStorage.getItem('tabs')));
}
if (window.localStorage.getItem('permissions')) {
	store.commit(types.PERM, window.localStorage.getItem('permissions'));
}
if (window.localStorage.getItem('user')) {
	store.commit(types.USER, window.localStorage.getItem('user'));
}

const router = new VueRouter({
	// mode: 'history',
	routes: routes
});

var config_obj = {}
Axios.get('./static/config.json').then((res) => {
	Vue.prototype.CONFIG = res.data;
	new Vue({
		el: '#app',
		store,
		router,
		render: h => h(App),
		mounted() {}
	})
});
Axios.get('./static/utils.json').then((res) => {
	Vue.prototype.UTILSJSON = res.data;
});

router.beforeEach((to, from, next) => {
	console.log("-----6666----", to, from, next,to.fullPath);
	if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
		if (store.state.token) { // 通过vuex state获取当前的token是否存在
			if(to.fullPath == "/login" || to.fullPath == "/"){
				next({
					path: '/processmain',
				})
			}else {
				next();
			}
		} else {
			next({
				path: '/login',
				query: {
					redirect: to.fullPath
				} // 将跳转的路由path作为参数，登录成功后跳转到该路由
			})
		}
	} else {
		if(store.state.token && (to.path == "/login"|| to.path == "/") && (to.query.type ==undefined || to.query.type == null)){
			next({
				path: '/processmain',
			})
		}else {
			next();
		}
	}
});
// Axios.defaults.withCredentials=true
Axios.defaults.timeout = 30000
// http request 拦截器
Axios.interceptors.request.use(
	config => {
		if (store.state.token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
			config.headers.Authorization = `${store.state.token}`;
			if (config.params === undefined || config.params === null) {
				config.params = {
					"timestamp": new Date().getTime()
				}
			} else {
				config.params.timestamp = new Date().getTime()
			}
		}
		return config;
	},
	err => {
		return Promise.reject(err);
	});

// http response 拦截器
Axios.interceptors.response.use(
	response => {
		return response;
	},
	error => {
		if (error.response) {
			switch (error.response.status) {
				case 401:
					// 返回 401 清除token信息并跳转到登录页面
					localStorage.clear();
					store.commit(types.LOGOUT);
					router.replace({
						path: '/login',
						query: router.currentRoute.query
					});
			}
		}
		if (error.response != null) {
			return Promise.reject(error) // 返回接口返回的错误信息
		}
	}
);

import {
	extend
} from 'umi-request';
const umirequest = extend({
	timeout: 30000,
});
// request拦截器, 改变url 或 options.
umirequest.interceptors.request.use(async (url, options) => {
	console.log("-------------拦截----------------------------->")
	let c_token = window.localStorage.getItem('token');
	if (c_token) {
		const headers = {
			'Content-Type': 'application/json',
			'Accept': 'application/json',
			'Authorization': c_token
		};
		return ({
			url: url,
			options: { ...options,
				headers: headers
			},
		});
	}
})
umirequest.interceptors.response.use((response) => {
	console.log("router.query---》",router.currentRoute.query)
	switch (response.status) {
		case 401:
			// 返回 401 清除token信息并跳转到登录页面
			localStorage.clear();
			store.commit(types.LOGOUT);
			router.replace({
				path: '/login',
				query: router.currentRoute.query
			});
			break
	}
	return response;
});


function hasPermission(menus, route) {
	if (route.menu) {
		/*
		 * 如果这个路由有menu属性,就需要判断用户是否拥有此menu权限
		 */
		return menus.indexOf(route.menu) > -1;
	} else {
		return true
	}
}

/**
 * 递归过滤异步路由表，返回符合用户菜单权限的路由表
 * @param asyncRouter
 * @param menus
 */
function filterAsyncRouter(asyncRouter, menus) {
	const accessedRouters = asyncRouter.filter(route => {
		//filter,js语法里数组的过滤筛选方法
		if (hasPermission(menus, route)) {
			if (route.children && route.children.length) {
				//如果这个路由下面还有下一级的话,就递归调用
				route.children = filterAsyncRouter(route.children, menus)
				//如果过滤一圈后,没有子元素了,这个父级菜单就也不显示了
				return (route.children && route.children.length)
			}
			return true
		}
		return false
	})
	return accessedRouters
}
